package cn.liuweiwei.controller;

import cn.liuweiwei.domain.User;
import cn.liuweiwei.service.UserService;
import cn.liuweiwei.util.JWTUtils;
import cn.liuweiwei.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("users")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/login/{username}/{password}")
    public Result login(@PathVariable("username") String username,
                        @PathVariable("password") String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        User loginUser = userService.login(user);
        if (Objects.isNull(loginUser)) {
            return Result.error("登陆失败、用户名或密码错误");
        }
        return Result.successWithObj(loginSuccess(loginUser));
    }

    private Map<String, String> loginSuccess(User loginUser) {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", loginUser.getUsername());
        map.put("userId", loginUser.getId() + "");
        map.put("token", JWTUtils.getToken(map));
        return map;
    }

}
